package client

import (
	"context"
	"regexp"
	"time"

	md "github.com/go-kratos/kratos/v2/metadata"
	"github.com/go-kratos/kratos/v2/middleware/metadata"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/registry"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	ggrpc "google.golang.org/grpc"
)

// NewGrpcClientConn .
func NewGrpcClientConn(dis registry.Discovery, serviceName string, source string) (*ggrpc.ClientConn, error) {
	return grpc.DialInsecure(
		context.Background(),
		grpc.WithEndpoint(getEndpointByServiceName(serviceName)),
		grpc.WithDiscovery(dis),
		grpc.WithMiddleware(
			tracing.Client(),
			metadata.Client(metadata.WithConstants(md.New(map[string]string{"x-md-global-app-name": source}))),
		),
		grpc.WithTimeout(time.Second*3),
	)
}

func getEndpointByServiceName(text string) string {
	reg := regexp.MustCompile(`\.api(\..+)?\.v[0-9]+\.`)
	re := reg.Split(text, -1)
	if len(re) > 1 {
		return "discovery:///" + re[0]
	}
	return ""
}
